import os
import shutil
import re
import pandas as pd
import configparser
import sys
import pystray
from PIL import Image
import threading
import ctypes
import psutil

def create_mutex(mutex_name):
    """创建全局互斥体"""
    mutex = ctypes.windll.kernel32.CreateMutexW(None, 1, mutex_name)
    if ctypes.windll.kernel32.GetLastError() == 183:
        # 互斥体已经存在，说明另一个实例已经在运行
        return False
    return True

def release_mutex(mutex):
    """释放全局互斥体"""
    ctypes.windll.kernel32.ReleaseMutex(mutex)

def sanitize_filename(filename):
    """清理文件名中的特殊字符"""
    return re.sub(r'[\\/*?:"<>|]', "", filename)

def save_config(input_folder, output_folder, archive_folder, enable_subfolders):
    config = configparser.ConfigParser()
    config['Paths'] = {
        'input_folder': input_folder,
        'output_folder': output_folder,
        'archive_folder': archive_folder,
        'enable_subfolders': str(enable_subfolders)
    }
    with open('config.ini', 'w') as configfile:
        config.write(configfile)

def get_config_paths():
    config = configparser.ConfigParser()
    config.read('config.ini')

    if 'Paths' not in config or 'input_folder' not in config['Paths'] or 'output_folder' not in config['Paths'] or 'archive_folder' not in config['Paths'] or 'enable_subfolders' not in config['Paths']:
        print("配置文件中缺少输入、输出、归档文件夹路径或子文件夹启用设置。请手动编辑 config.ini 文件以添加这些路径。")
        input_folder = input("选择输入文件夹路径: ")
        output_folder = input("选择输出文件夹路径: ")
        archive_folder = input("选择归档文件夹路径: ")
        enable_subfolders = input("启用子文件夹功能 (True/False): ").strip().lower() == 'true'
        save_config(input_folder, output_folder, archive_folder, enable_subfolders)
    else:
        input_folder = config['Paths']['input_folder']
        output_folder = config['Paths']['output_folder']
        archive_folder = config['Paths']['archive_folder']
        enable_subfolders = config['Paths'].getboolean('enable_subfolders')

    return input_folder, output_folder, archive_folder, enable_subfolders

def process_files(input_folder, output_folder, enable_subfolders):
    # 确保输出文件夹存在
    os.makedirs(output_folder, exist_ok=True)

    # 遍历输入文件夹中的所有文件
    for filename in os.listdir(input_folder):
        if filename.endswith(".xlsx"):
            # 构造完整的文件路径
            file_path = os.path.join(input_folder, filename)

            try:
                # 提取第1行第20列的数据（注意：pandas的索引是从0开始的）
                df = pd.read_excel(file_path, engine='openpyxl', header=None, nrows=1)
                name = df.iloc[0, 19]

                # 提取RTS之前的部分
                rts_index = str(name).find("RTS")
                if rts_index != -1:
                    name = str(name)[:rts_index].strip()

                # 清理文件名中的特殊字符
                sanitized_name = sanitize_filename(str(name))
                new_filename = f"{sanitized_name}_{filename}"
                new_file_path = os.path.join(output_folder, new_filename)

                # 直接复制文件以保留格式和内容
                shutil.copy(file_path, new_file_path)
                print(f"Copied to: {new_file_path}")

                # 检查文件大小
                if os.path.exists(new_file_path):
                    file_size = os.path.getsize(new_file_path)
                    print(f"File size: {file_size} bytes")
                else:
                    print(f"Error: File not created at {new_file_path}")

                # 构造同名的csv和pdf文件名
                base_name = new_filename[:-5]  # 去掉.xlsx后缀
                csv_filename = f"{base_name}.csv"
                pdf_filename = f"{base_name}.pdf"

                # 初始化 new_csv_file_path 和 new_pdf_file_path
                new_csv_file_path = None
                new_pdf_file_path = None

                # 复制同名的csv文件
                csv_file_path = os.path.join(input_folder, filename[:-5] + ".csv")
                if os.path.exists(csv_file_path):
                    new_csv_file_path = os.path.join(output_folder, csv_filename)
                    shutil.copy(csv_file_path, new_csv_file_path)
                    print(f"Copied CSV file to: {new_csv_file_path}")

                # 复制同名的pdf文件
                pdf_file_path = os.path.join(input_folder, filename[:-5] + ".pdf")
                if os.path.exists(pdf_file_path):
                    new_pdf_file_path = os.path.join(output_folder, pdf_filename)
                    shutil.copy(pdf_file_path, new_pdf_file_path)
                    print(f"Copied PDF file to: {new_pdf_file_path}")

                # 根据文件名中的关键词移动文件到相应的子文件夹
                if enable_subfolders:
                    move_to_subfolder(new_file_path, output_folder)
                    if new_csv_file_path:
                        move_to_subfolder(new_csv_file_path, output_folder)
                    if new_pdf_file_path:
                        move_to_subfolder(new_pdf_file_path, output_folder)

            except Exception as e:
                print(f"Error processing file {filename}: {e}")

def archive_and_clear_input_folder(input_folder, archive_folder, enable_subfolders):
    # 确保归档文件夹存在
    os.makedirs(archive_folder, exist_ok=True)

    # 遍历输入文件夹中的所有文件
    for filename in os.listdir(input_folder):
        file_path = os.path.join(input_folder, filename)
        archive_file_path = os.path.join(archive_folder, filename)
        try:
            # 移动文件到归档文件夹
            shutil.move(file_path, archive_file_path)
            print(f"Archived to: {archive_file_path}")

            # 根据文件名中的关键词移动文件到相应的子文件夹
            if enable_subfolders:
                move_to_subfolder(archive_file_path, archive_folder)

        except Exception as e:
            print(f"Error archiving file {filename}: {e}")

def move_to_subfolder(file_path, base_folder):
    """根据文件名中的关键词移动文件到相应的子文件夹"""
    filename = os.path.basename(file_path)
    if "Day" in filename:
        subfolder = "日报"
    elif "Week" in filename:
        subfolder = "周报"
    elif "Month" in filename:
        subfolder = "月报"
    elif "Year" in filename:
        subfolder = "年报"
    else:
        return

    subfolder_path = os.path.join(base_folder, subfolder)
    os.makedirs(subfolder_path, exist_ok=True)
    new_file_path = os.path.join(subfolder_path, filename)
    shutil.move(file_path, new_file_path)
    print(f"Moved to: {new_file_path}")

def create_systray_icon():
    image = Image.open("icon.png")
    menu = (
        #移除exit按钮
    )
    icon = pystray.Icon("name", image, "My System Tray Icon", menu)
    icon.run()

def hide_console_window():
    # 使用 ctypes 隐藏控制台窗口
    whnd = ctypes.windll.kernel32.GetConsoleWindow()
    if whnd != 0:
        ctypes.windll.user32.ShowWindow(whnd, 0)
        ctypes.windll.kernel32.CloseHandle(whnd)

def terminate_previous_instance(mutex_name):
    """终止之前的实例"""
    for proc in psutil.process_iter(['pid', 'name']):
        if proc.info['name'] == 'NameConversion.exe':
            try:
                p = psutil.Process(proc.info['pid'])
                p.terminate()
                p.wait()
                print(f"Terminated previous instance with PID {proc.info['pid']}")
            except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
                pass

def main():
    # 创建全局互斥体
    mutex_name = "NameConversionMutex"
    mutex = ctypes.windll.kernel32.CreateMutexW(None, 1, mutex_name)
    if ctypes.windll.kernel32.GetLastError() == 183:
        # 互斥体已经存在，说明另一个实例已经在运行
        print("另一个实例已经在运行。终止之前的实例并启动新的实例。")
        terminate_previous_instance(mutex_name)
        # 重新创建互斥体
        mutex = ctypes.windll.kernel32.CreateMutexW(None, 1, mutex_name)

    try:
        hide_console_window()
        input_folder, output_folder, archive_folder, enable_subfolders = get_config_paths()
        process_files(input_folder, output_folder, enable_subfolders)
        archive_and_clear_input_folder(input_folder, archive_folder, enable_subfolders)
        create_systray_icon()
    finally:
        # 释放互斥体
        release_mutex(mutex)

if __name__ == "__main__":
    main()
